package org.com.blbl.Gender;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class GenderReducer extends Reducer<Text,IntWritable,Text,Text>{
    private Map<String, Integer> genderCountMap = new HashMap<>();
    private int totalCount = 0;

    @Override
    public void reduce(Text key, Iterable<IntWritable> values, Context context) {
        int sum = 0;
        for (IntWritable val : values) {
            sum += val.get();
        }
        genderCountMap.put(key.toString(), sum);
        totalCount += sum;
    }

    @Override
    protected void cleanup(Context context) throws IOException, InterruptedException {
        int maleCount = genderCountMap.getOrDefault("男", 0);
        int femaleCount = genderCountMap.getOrDefault("女", 0);

        double malePercentage = (maleCount * 100.0) / totalCount;
        double femalePercentage = (femaleCount * 100.0) / totalCount;

        String output = String.format("男生占比：%.2f%% 女生占比：%.2f%%", malePercentage, femalePercentage);
        context.write(new Text("性别统计结果"), new Text(output));
    }

}
